/**
 * Created by xinhuang on 15/6/14.
 */
(function (angular) {
  'use strict';

  angular.module('services.customActivity', [
    'services.customActivity.realtime',
    'services.customActivity.summary'
  ])
    .service('provinceAutoComplete', provinceAutoComplete)
    .service('checkboxManager', checkboxManager)
    .service('previewEditor', previewEditor);

  function provinceAutoComplete($http) {
    var that = this;

    that.selectedItem = null;
    that.searchText = null;
    that.querySearch = querySearch;
    that.provinces = [];
    that.getProvince = getProvince;
    that.getSelectedProvince = getSelectedProvince;

    function getSelectedProvince(proIds){
      var selectedProvince = [];
      angular.forEach(proIds, function(proId){
        angular.forEach(that.provinces, function(province){
          if(proId === province.provinceCode){
            selectedProvince.push(province);
          }
        });
      });

      return selectedProvince;
    }

    function getProvince(){
      $http.get('/sas/realtime/common/province/query')
        .success(function(res){
          that.provinces = res.data;
        });
    }

    function querySearch(query) {
      return query ? that.provinces.filter(createFilterFor(query)) : [];
    }

    function createFilterFor(query) {
      var input = angular.lowercase(query);
      return function(province){
        return (province.provinceName.indexOf(input) === 0) ||
        (province.provinceSpell.indexOf(input) === 0) ||
        (province.provinceShorthand.indexOf(input) === 0);
      }
    }
  }

  function checkboxManager(previewEdited){
    var that = this;

    that.selectParent = function(parentModule){
      previewEdited.state = false;
      angular.forEach(parentModule.childModule, function(child){
        child.selected = parentModule.selected;
      });
    };

    that.selectChild = function(parentModule){
      previewEdited.state = false;
      parentModule.selected = true;
      angular.forEach(parentModule.childModule, function(child){
        if(is.falsy(child.selected)){
          parentModule.selected = false;
        }
      });
    }
  }

  function previewEditor(){
    var that = this;

    that.instance = {};

    that.pageGenarator = function(ele){
      that.instance = $(ele).ckDrag();
    };

    that.addDragEvent = function(){
      that.instance.addDragEvent();
    };

    that.layoutGenerator = function(){
      return that.instance.getResultDom();
    }
  }
})(angular);